<?php
// header("Content-type:text/html;charset=utf-8");  
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
	/*---------首页---------*/

		public function index()
		{	
			
			login('请先登录');
			$message=M('t_msg')->find();			
			$User_Profile=M('t_agent')->where('accounts='.$_SESSION['accounts'])->find();	//登录用户的信息
			
            $underling=M('t_agent')->where('referrer='.$User_Profile['accounts'])->Count();
            if($_SESSION['agencylv']==100)
			{	
				$underling=M('t_agent')->where("agencylv != 100")->Count();	//统计所有代理的数量

			}
				
			$sql = array();
  	      	$v = get_flo(M());
			$v($sql, $_SESSION['accounts']);
			//dump(count($sql));die;
			
			if ($_SESSION['agencylv']==0 && count($sql)!=0) {//总代理旗下所有代理的充值总和

				foreach ($sql as $k => $v) {
				   	    $accounts[] = $v['accounts'];
				 }
				$where['oper_account'] = array('in',$accounts);

                $reca =  M('yp_apply_order')->where($where)->where("order_status=1")->sum('order_money');
                $rechargetotal = $reca*100;
                //dump($rechargetotal);die;
                M("","","DB_CONFIG0")->execute("update t_agent set rechargetotal='$rechargetotal' where accounts=".$User_Profile['accounts']);

				$underling=count($sql);	//统计总代理下级代理的数量
			}
			

			if ($_SESSION['agencylv']>=1 && $_SESSION['agencylv']<=10 && count($sql)!=0) {//一级代理普通代理旗下两级代理的充值总和

                   $resultArr = array();
				   foreach ($sql as $key => $value)
				   {
				       if ($value['floor'] >=3 )
				       {
				           continue;
				       }
				       else
				       {
				           $resultArr[] = $value;
				       }
				   }
				   foreach ($resultArr as $k => $v) {
				   	    $accounts[] = $v['accounts'];
				   }
				$where['oper_account'] = array('in',$accounts);
                $reca =  M('yp_apply_order')->where($where)->where("order_status=1")->sum('order_money');
                $rechargetotal = $reca*100;
                //dump($rechargetotal);die;
                M("","","DB_CONFIG0")->execute("update t_agent set rechargetotal='$rechargetotal' where accounts=".$User_Profile['accounts']);
				//dump($totalhistory);die;
				
			}

			$cur_date = (date('Y-m-d'));
			
			$sum=M('t_agent_add_cards_to_agent')->where("recipient=".$User_Profile['accounts'] ." AND regtime >= '{$cur_date}' ")->sum('gems');//今日充值数

			
			
			/*------------------本代理账户的充值总数写进代理表,当总数达到某一值时改变返利比例------------------*/
			$total=M('yp_apply_order')->where('order_status=1 and oper_account='.$User_Profile['accounts'])->sum('order_money');
            $totalhistory = $total*100;
            //dump($totalhistory);die;
		    M('t_agent')->execute("update t_agent set totalhistory='$totalhistory' where accounts=".$User_Profile['accounts']);
            
            if($_SESSION['agencylv']!=100){
	            $cate = array();
	  	     	$va = get_bate(M());
	  	     	$count = 0;
				$va($cate, $User_Profile['referrer'], $count);
		    }
		    /*-----------登陆用户的返利额度及上级，上上级的返利额度写进返利额度表---------------*/
		    
		    $quota = M('t_rebate_quota')->where("id =".$User_Profile['accounts'])->count();//登录用户的返利额度数据个数
		    
		    if($quota<6)
	            {
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",2000,0,0.1,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",5000,2000,0.12,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",10000,5000,0.15,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",20000,10000,0.15,0.04)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",50000,20000,0.15,0.05)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",10000000,50000,0.2,0.05)");
	            }
		    if($count>=1){
	            $superior    =M('t_agent')->where('accounts='.$User_Profile['referrer'])->find();
	            //登录用户的上级代理数据
	            $quota1 = M('t_rebate_quota')->where("id =".$superior['accounts'])->count();
	            //登录用户的上级代理返利额度数据个数
	            if($quota1<6)
	            {
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",2000,0,0.1,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",5000,2000,0.12,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",10000,5000,0.15,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",20000,10000,0.15,0.04)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",50000,20000,0.15,0.05)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",10000000,50000,0.2,0.05)");
	            }
	        }
	        if($count>=2){
			    $up_superior =M('t_agent')->where('accounts='.$superior['referrer'])->find();
			    //登录用户的上上级代理数据
	            $quota2 = M('t_rebate_quota')->where("id =".$up_superior['accounts'])->count();
	            //登录用户的上上级代理返利额度数据个数
	            if($quota2<6)
	            {
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",2000,0,0.1,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",5000,2000,0.12,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",10000,5000,0.15,0.03)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",20000,10000,0.15,0.04)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",50000,20000,0.15,0.05)");
	            	M('','','DB_CONFIG0')->execute("insert into t_rebate_quota(id,top_limit,botton_limit,first_upper_rebate,second_upper_rebate) values(".$User_Profile['accounts'].",10000000,50000,0.2,0.05)");
	            }
            }
            $purview = M("t_authority_configuration")->where("grade=".$User_Profile['agencylv'])->find();

            //我的下级返利额度，下下级返利额度，固定值返利
            $zong =M('t_agent')->where('accounts='.$User_Profile['accounts'])->find();
            $quotaone = M('t_rebate_quota')->where("id =".$User_Profile['accounts']." AND top_limit >".$zong['rechargetotal']." AND botton_limit <=".$zong['rechargetotal'])->find();
             //dump($quotaone['first_upper_rebate']);die;
            $first = $quotaone['first_upper_rebate']*100;
            $second = $quotaone['second_upper_rebate']*100;
            $disbate = $quotaone['disbate']*100;

			$this->assign('first',$first);
			$this->assign('second',$second);
			$this->assign('disbate',$disbate);
			$this->assign('purview',$purview);
			$this->assign('underling',$underling);
			$this->assign('User_Profile',$User_Profile);
			$this->assign('message',$message);
			$this->assign('sum',$sum);
			$this->display();
		}
		/*---------充值页面---------*/
		public function searchplayer()
		{	
			login('请先登录');
			$this->display();
		}
		/*---------信息页面---------*/
		public function chargegoldtoplayer()
		{
			login('请先登录');
			if(IS_POST)
			{
				$userid=I('post.userid');
				if($userid=="")
				{
					error_add('您好,请正确输入您要赠送玩家的ID');
				}		
				$users=M('','t_users','DB_CONFIG1')->where('userid='.$userid)->find();
				if($users=="")
				{
					error_add('您好,请正确输入您要赠送玩家的ID');
				}else
				{
					$sql=M("","t_","DB_CONFIG1")->query('select * from t_users where userid='.$userid);
				}	
			}
				$this->assign('sql',$sql);
				$this->display();
		}
		/*---------充值处理---------*/
		public function money_settle()
		{
			if($_POST['userid']=="")
			{
				error('充值信息为空，请重新输入玩家ID');
			}
			if(IS_POST)
			{
				$Regems=I('post.gems2');
				$userid=I('post.userid');
				if($Regems<=0)
				{
					error_add('请输入正确的充值数量');
				}else
				{
					$games_users=M("","","DB_CONFIG1")->query('select * from t_users where userid='.$userid); 							//游戏用户信息
					$agent=M('','','DB_CONFIG0')->query('select *from t_agent where accounts='.$_SESSION['accounts']);					//代理信息
					if($Regems>$agent[0]['gems'])
					{
						error_add('您好，您的账号上钻石数不足，无法充值，请联系上级或 自行充值');
					}				
					$sum=$games_users[0]['gems']+$Regems;																	//充值后的玩家钻石数量
					$remain=$agent[0]['gems']-$Regems;																		//充值后总代理的钻石数量
					if(M("","","DB_CONFIG1")->execute("update t_users set gems='$sum' where userid=%d",$userid))
					{
						if(M('','','DB_CONFIG0')->execute("update t_agent set gems={$remain} where accounts=%d",$_SESSION['accounts']))
						{
							$benefactor=$agent[0]['accounts'];
							$recipient=$games_users[0]['userid'];
							$game=trim(I('post.game'));
							$name=trim(I('post.name'));
							$gems_front=$agent[0]['gems'];														       //代理充值前的钻石
							$sql=M('','','DB_CONFIG0')->execute("insert into t_agent_add_cards_to_user(manner,benefactor,recipient,gems,game,name,gems_front,gems_queen,accept_front,accept_queen)values('2',{$benefactor},{$recipient},{$Regems},{$game},'$name',{$gems_front},{$remain},{$Regems},{$sum})");
							if($sql)
							{
								achieve($games_users,$Regems);
							}
						}
					}
					else
					{
						error_add('系统繁忙,请重新充值');
					}
				}
			}
			$this->display();
		}
		/*---------添加代理---------*/
		public function creatuser()
		{	   
			login('请先登录');

		    $this->display();	
		}
		/*---------添加代理跳转---------*/
		public function checkCreatuser($phone,$rname,$nick,$pword,$type,$agentid,$region)
		{
			
			$password = md5($pword);
	         
			$accounts = 10000+rand(1,9000)*rand(1,10);
		    $chongfu = M('t_agent')->where("accounts=".$accounts)->find();
			$row=M('t_agent')->where("phone=".$phone)->find();

			if($row !=""){
				$data['state'] = 1;
			}
			elseif ($chongfu != "") {
				$data['state'] = 1;
			}
			else
			{
				
				if(M('','','DB_CONFIG0')->execute("insert into t_agent(agencylv,accounts,username,password,nickname,region,referrer,phone)values('$type','$accounts','$rname','$password','$nick','$region','$agentid','$phone')"))
				{
					$data['state'] = 2;
				}else{
					$data['state'] = 3;
				}
			}  
			$this->ajaxReturn($data);
		}
		/*---------分享链接页面---------*/
		public function addition()
		{
			if(IS_POST)
			{
				$phone_one=I('post.phone') ;
				if(strlen(I('post.phone')<11))
				{
					error_add('请输入正确的手机号');
				}
				if(strlen(I('post.password'))<6 || I('post.passwordd')<6)
				{
					error_add('您的密码不符合规范性');		
				}
				if(I('post.password') != I('post.passwordd'))
				{
					error_add('两次密码不同，请重新输入');
				}
				if(I('post.username')==""  || I('post.password')=="" || I('post.nickname')=="" || I('post.phone')=="" || I('post.game')=="")
				{
					error_add('请详细填写信息');
				}
				if($_POST['referrer']=="")
				{
					error_add('推荐人ID错误，请确定分享链接');die;
				}				
				$account=M('t_agent')->where('accounts='.$_POST['referrer'])->find();
				if($account=="")
				{
					error_add('资料填写不正确，请确定推荐人是否存在');die;
				}

				
					else
					{
						$agencylv=I('post.agencylv');
						$gametype=I('post.game');
						do
						{
							$accounts = 10000+rand(1,9000)*rand(1,10);
							$accounts_1 = M('','','DB_CONFIG0')->query('select count(*) from t_agent where accounts = '.$accounts);
						}while ($accounts_1[0]['accounts'] > 0);	
						$username=trim(I('post.username'));
						$password=MD5(trim(I('post.password')));
						$nickname=trim(I('post.nickname'));
						$region=trim(I('post.region'));		
						$referrer=trim(I('post.referrer'));
						$phone=trim(I('post.phone')); //以上为数据接受
						$phone_1=M('t_agent')->where('phone='.$phone)->find();
						if($phone_1!="")
						{
							error_add('电话号已存在，请重新输入');
						}
						// if($_SESSION['agencylv']>$agencylv)
						// {
						// 	error_add('抱歉，您只能添加您的下级代理');
						// }
						$sql=M('','','DB_CONFIG0')->execute("insert into t_agent(agencylv,game,accounts,username,password,nickname,region,referrer,phone)values('$agencylv','$gametype','$accounts','$username','$password','$nickname','$region','$referrer','$phone')");
						if($sql)
						{
							myadmin_login('代理添加成功');die;
						}
						else
						{
							error_add('填写的信息错误，请重新输入');
						}
					}
				
			}
		$this->display();
		}
		/*---------我的代理---------*/
		public function myadmin()     
		{
             
			login('请先登录');
			$one=M("","t_agent","DB_CONFIG0")->where('accounts='.$_SESSION['accounts'])->find(); 
  	      	$sql=M('','','DB_CONFIG0')->query("select * from t_agent where referrer=".$one['accounts']);//查出 userid 不等于登录庄户的ID 的数据
  	      	$quota = M('t_rebate_quota')->where("id =".$one['accounts']." AND top_limit >".$one['rechargetotal']." AND botton_limit <=".$one['rechargetotal'])->find();
  	      	//dump($sql);die;
			if($one['agencylv']==100){//当用户的等级是总权限的时候 
				$sql=M('','','DB_CONFIG0')->query("select * from t_agent where agencylv!=100  order by agencylv asc");//查出 userid 不等于登录庄户的ID 的数据
			}
			if($one['agencylv']==0){//当用户的等级是总代理的时候 
                $sql = array();
	  	      	$v = get_str(M());//自定义函数  获取下级所有ID
				$v($sql, $_SESSION['accounts'],0);
			}
			//dump($sql);die;
			if(IS_POST)
			{
				if(I('post.type')==1)
				{   
				    // $sql=M('','','DB_CONFIG0')->query("select * from t_agent where referrer="'. $one['accounts'].'" order by gems desc");
				    $sql=M('','t_agent','DB_CONFIG0')->where('referrer='.$one['accounts'])->order('gems desc')->select();
				    //查出 userid 
				    //dump($sql);die;
					if($one['agencylv']==0){//当用户的等级是总代理的时候 
					    $sql = array();
						$cate ="select * from t_agent where referrer= ? order by gems desc";
  	      	            $v = get_str(M(),true,$cate);//自定义函数  获取下级所有ID
						$v($sql, $_SESSION['accounts']);//查出 userid 不等于登录庄户的ID 的数据
					    //dump($sql);die;
					}
					if($one['agencylv']==100)//当用户的等级是总权限的时候
					{
						$sql=M('','','DB_CONFIG0')->query("select * from t_agent where agencylv!=100  order by gems desc");//查出 userid 不等于登录庄户的ID 的数据
					}
				}
				
				if(I('post.type')=="")
				{   
					$sql=M('','','DB_CONFIG0')->query("select * from t_agent where referrer=".$one['accounts']);//查出 userid 
					if($one['agencylv']==0){//当用户的等级是总代理的时候 
					$sql = array();
		  	      	$v = get_str(M());//自定义函数  获取下级所有ID
					$v($sql, $_SESSION['accounts']);
				    }

					if($one['agencylv']==100)
					{
						$sql=M('','','DB_CONFIG0')->query("select * from t_agent where agencylv!=100  order by agencylv asc");//查出 userid 不等于登录庄户的ID 的数据
					}
				}
			}
			if(I('post.accounts')!="" || I('post.username')!="")
			{
				$sql=M('','','DB_CONFIG0')->query("SELECT * FROM t_agent WHERE accounts LIKE '%".I('post.accounts')."%' and username like '%".I('post.username')."%' AND referrer=".$one['accounts']);
                if($one['agencylv']==0){//当用户的等级是总代理的时候 
				$sql = array();
				$cate = "select * from t_agent where referrer= ? and accounts LIKE '%".I('post.accounts')."%' and username like '%".I('post.username')."%'";
      	        $v = get_str(M(),true,$cate);//自定义函数  获取下级所有ID
				$v($sql, $_SESSION['accounts']);//查出 userid 不等于登录庄户的ID 的数据
			    }
                 //dump($sql);die;
				if($one['agencylv']==100)//当用户的等级是总代理的时候  
				{
					$sql=M('','','DB_CONFIG0')->query("SELECT * FROM t_agent WHERE accounts LIKE '%".I('post.accounts')."%' and username like '%".I('post.username')."%' and agencylv!=100");

				}
			}
			$purview = M("t_authority_configuration")->where("grade=".$one['agencylv'])->find();
            //dump($purview);die;
			$this->assign('purview',$purview);
			$this->assign('quota',$quota);
			$this->assign('one',$one);
			$this->assign('sql',$sql);
			$this->display();
		}
		
		/*         我下级给我的返利         */
		public function subordinate()
		{
			login('请先登录');

            
			$sqls = array();
			$sql1 = "select id,benefactor,recipient,times,gems,order_no,superior,up_id,superior_state from t_rebate where superior!=0 AND up_id=".$_SESSION['accounts'];
			$sql2 = "select id,benefactor,recipient,times,gems,order_no,accumulative,superior_id,state from t_rebate where accumulative!=0 AND superior_id=".$_SESSION['accounts'];
			if($_SESSION['agencylv'] == 0){
				$sql3 = "select id,benefactor,recipient,times,gems,order_no,todisbate,distributor,dis_state from t_rebate where todisbate!=0 AND distributor=".$_SESSION['accounts'];
			}
			array_push($sqls, $sql1);
			array_push($sqls, $sql2);
			if($_SESSION['agencylv'] == 0){
				array_push($sqls, $sql3);
			}
  	      	$var = get_age(M(), $sqls);//调用函数
  	      	$rebate = array();
  	      	
  	      	foreach($var as $value){  
			    foreach($value as $v){  
			         $rebate[]=array_values($v);  //键名不同无法循环，在这里删除所有键名，用数字代替
			    }  
			}
			$rebate = sortArrayDesc($rebate,3);  //调用函数，按时间倒叙排序
            //dump($rebate);die;

			if(IS_POST)
			{
				if(I('post.type')!="")
				{				
					if(I('post.type')==1)
					{
						
						$sqls = array();
						$sql1 = "select id,benefactor,recipient,times,gems,order_no,superior,up_id,superior_state from t_rebate where superior!=0 AND superior_state=1 AND up_id=".$_SESSION['accounts'];
						$sql2 = "select id,benefactor,recipient,times,gems,order_no,accumulative,superior_id,state from t_rebate where accumulative!=0 AND state=1 AND superior_id=".$_SESSION['accounts'];
						if($_SESSION['agencylv'] == 0){
							$sql3 = "select id,benefactor,recipient,times,gems,order_no,todisbate,distributor,dis_state from t_rebate where todisbate!=0 AND dis_state=1 AND distributor=".$_SESSION['accounts'];
						}
						array_push($sqls, $sql1);
						array_push($sqls, $sql2);
						if($_SESSION['agencylv'] == 0){
							array_push($sqls, $sql3);
						}
			  	      	$var = get_age(M(), $sqls);//调用函数
			  	      	$rebate = array();
			  	      	
			  	      	foreach($var as $value){  
						    foreach($value as $v){  
						         $rebate[]=array_values($v);  //键名不同无法循环，在这里删除所有键名，用数字代替
						    }  
						}
					}	
					
					if(I('post.type')==0)
					{
						$sqls = array();
						$sql1 = "select id,benefactor,recipient,times,gems,order_no,superior,up_id,superior_state from t_rebate where superior!=0 AND superior_state=0 AND up_id=".$_SESSION['accounts'];
						$sql2 = "select id,benefactor,recipient,times,gems,order_no,accumulative,superior_id,state from t_rebate where accumulative!=0 AND state=0 AND superior_id=".$_SESSION['accounts'];
						if($_SESSION['agencylv'] == 0){
							$sql3 = "select id,benefactor,recipient,times,gems,order_no,Todisbate,Distributor,dis_state from t_rebate where Todisbate!=0 AND dis_state=0 AND Distributor=".$_SESSION['accounts'];
						}
						array_push($sqls, $sql1);
						array_push($sqls, $sql2);
						if($_SESSION['agencylv'] == 0){
							array_push($sqls, $sql3);
						}
			  	      	$var = get_age(M(), $sqls);//调用函数
			  	      	$rebate = array();
			  	      	
			  	      	foreach($var as $value){  
						    foreach($value as $v){  
						         $rebate[]=array_values($v);  //键名不同无法循环，在这里删除所有键名，用数字代替
						    }  
						}
					}
					
				}
				if(I('post.accounts')!="")
				{  
						$sqls = array();
						$sql1 = "select id,benefactor,recipient,times,gems,order_no,superior,up_id,superior_state from t_rebate where superior!=0  AND up_id=".$_SESSION['accounts']." AND recipient like '%".I('post.accounts')."%'";
						$sql2 = "select id,benefactor,recipient,times,gems,order_no,accumulative,superior_id,state from t_rebate where accumulative!=0 AND  superior_id=".$_SESSION['accounts']." AND recipient like '%".I('post.accounts')."%'";
						if($_SESSION['agencylv'] == 0){
							$sql3 = "select id,benefactor,recipient,times,gems,order_no,Todisbate,Distributor,dis_state from t_rebate where Todisbate!=0  AND Distributor=".$_SESSION['accounts']." AND recipient like '%".I('post.accounts')."%'";
						}
						array_push($sqls, $sql1);
						array_push($sqls, $sql2);
						if($_SESSION['agencylv'] == 0){
							array_push($sqls, $sql3);
						}
			  	      	$var = get_age(M(), $sqls);//调用函数
			  	      	$rebate = array();
			  	      	
			  	      	foreach($var as $value){  
						    foreach($value as $v){  
						         $rebate[]=array_values($v);  //键名不同无法循环，在这里删除所有键名，用数字代替
						    }  
						}
						
									
				}
				if(I('post.sdate')!="" AND I('post.edate')!="")
				{	
					    $a = I('post.sdate'); $b = I('post.edate');
						$sqls = array();
						$sql1 = "select id,benefactor,recipient,times,gems,order_no,superior,up_id,superior_state from t_rebate where superior!=0 AND up_id=".$_SESSION['accounts']." AND times between '$a' and '$b'";
						$sql2 = "select id,benefactor,recipient,times,gems,order_no,accumulative,superior_id,state from t_rebate where accumulative!=0 AND superior_id=".$_SESSION['accounts']." AND times between '$a' and '$b'";
						if($_SESSION['agencylv'] == 0){
							$sql3 = "select id,benefactor,recipient,times,gems,order_no,Todisbate,Distributor,dis_state from t_rebate where Todisbate!=0 AND Distributor=".$_SESSION['accounts']." AND times between '$a' and '$b'";
						}
						array_push($sqls, $sql1);
						array_push($sqls, $sql2);
						if($_SESSION['agencylv'] == 0){
							array_push($sqls, $sql3);
						}
			  	      	$var = get_age(M(), $sqls);//调用函数
			  	      	$rebate = array();
			  	      	
			  	      	foreach($var as $value){  
						    foreach($value as $v){  
						         $rebate[]=array_values($v);  //键名不同无法循环，在这里删除所有键名，用数字代替
						    }  
						}
				}
			}

			$this->assign('rebate',$rebate);
			$this->display();
		}
		/*-------------返利结算------------------*/
		public function settle()
		{   
		    // $rebate=M('t_rebate')->where('id='.I('get.id'))->find();//登录用户可以返利的钻石die;
			// $sum=$rebate['accumulative']+$message['gems'];//获得返利我的钻石总数
			
			$message=M('t_agent')->where('accounts='.$_SESSION['accounts'])->find();//登录用户的基本信息]
			
			$sqls_1 = array();//找到所有下级的返利数量
			
			$sql1 = "select superior from t_rebate where superior_state=0 AND up_id=".$_SESSION['accounts'];
			$sql2 = "select accumulative from t_rebate where state=0 AND superior_id=".$_SESSION['accounts'];
			if($_SESSION['agencylv'] == 0){
				$sql3 = "select Todisbate from t_rebate where Dis_state=0 AND Todisbate!=0 AND Distributor=".$_SESSION['accounts'];
			}
			array_push($sqls_1, $sql1);
			array_push($sqls_1, $sql2);
			if($_SESSION['agencylv'] == 0){
				array_push($sqls_1, $sql3);
			}
			
			$var_1 = get_age(M(), $sqls_1);//调用函数
  	      	$sun = array();
  	      	
  	      	foreach($var_1 as $val){  
			    foreach($val as $v){  
			         foreach($v as $k){  
			               $sun[]=$k;  
			         }  
			    }  
			}
            $suns = (array_sum($sun));
            ////////////////////
            $sum = $message['gems'] + $suns; //获得所有返利后的钻石总数
            //dump($suns);die;    

            

			if($suns == 0){

                 subordinate('您已将返利全部领取');
			}else{
				if(M("","","DB_CONFIG0")->execute("update t_agent set gems='$sum' where accounts=".$_SESSION['accounts']))
				{
					M("","","DB_CONFIG0")->execute("update t_rebate set superior_state=1 where superior!=0 AND up_id=".$_SESSION['accounts']);
					M("","","DB_CONFIG0")->execute("update t_rebate set state=1 where accumulative!=0 AND superior_id=".$_SESSION['accounts']);
					if($_SESSION['agencylv'] == 0){
						M("","","DB_CONFIG0")->execute("update t_rebate set Dis_state=1 where Todisbate!=0 AND Distributor=".$_SESSION['accounts']);
					}

					subordSuns($suns);//告知代理有多少返利领取成功
				}else
				{
					subordinate('系统繁忙，请您重再次领取');
				}
			}	
		}
		
		/*---------下级代理的充钻记录---------*/
		public function agentcharge()
		{
			login('请先登录');
			$daili=M('t_agent_add_cards_to_agent');
			if($_GET['accounts']=="")
			{   
				$sql=$daili->where('superior='.$_SESSION['accounts'])->order('regtime desc')->select();//SQL 查询语句
				if($_SESSION['agencylv']==0)
				{
					$cate = array();
	                $va = get_str(M());
	                $va($cate,$_SESSION['accounts']);
	                //dump($cate);die;
					$sqls = array();
					foreach ($cate as $key => $value) {
						$sql1 = "select * from t_agent_add_cards_to_agent where recipient =".$value['accounts'];
						array_push($sqls, $sql1);
					}
		  	      	$var = get_age(M(), $sqls);//调用函数
		  	      	$sql = array();
		  	      	
		  	      	foreach($var as $value){  
					    foreach($value as $v){  
					         $sql[]=$v;  
					    }  
					}
				}	
			    
				//dump($sql1);die;

				if($_SESSION['agencylv']==100)
				{
					$sql=$daili->order('regtime desc')->select();
				}

				$sql = sortArrayDesc($sql,'regtime');//调用排序函数		

				if(IS_POST)
				{
					if(I('post.type')!="")
					{
						
						if(I('post.type')==1)
						{ 
							$sql=$daili->where('superior='.$_SESSION['accounts'])->order('gems desc')->select();
							if($_SESSION['agencylv']==0)
							{
								$cate = array();
				                $va = get_str(M());
				                $va($cate,$_SESSION['accounts']);
				                //dump($cate);die;
								$sqls = array();
								foreach ($cate as $key => $value) {
									$sql1 = "select * from t_agent_add_cards_to_agent where recipient =".$value['accounts'];
									array_push($sqls, $sql1);
								}
					  	      	$var = get_age(M(), $sqls);//调用函数
					  	      	$sql = array();
					  	      	
					  	      	foreach($var as $value){  
								    foreach($value as $v){  
								         $sql[]=$v;  
								    }  
								}
								$sql = sortArrayDesc($sql,'gems');//调用排序函数	
							}
							//dump($sqls);die;
								

							if($_SESSION['agencylv']==100)
							{
								$sql=$daili->order('gems desc')->select();
							}
						}
						
					}
					if(I('post.accounts')!="")
					{
                        $w['recipient']=array('like','%'.I('post.accounts').'%');//把数据写到空数组去
					    $sql=$daili->where($w)->where('superior='.$_SESSION['accounts'])->select();

						if($_SESSION['agencylv']==0)
						{
						    $sqls = array();
							foreach ($cate as $key => $value) {
					
								$sql1 = "select * from t_agent_add_cards_to_agent where recipient =".$value['accounts']." and recipient LIKE '%".I('post.accounts')."%'";
								//dump($sql1);die;
								array_push($sqls, $sql1);
							}
							
				  	      	$var = get_age(M(), $sqls);//调用函数
				  	      	$sql = array();
				  	      	
				  	      	foreach($var as $value){  
							    foreach($value as $v){  
							         $sql[]=$v;  
							    }  
							}
						}
							//dump($sqls);die;

						if($_SESSION['agencylv']==100)
						{
						    
							$sql=$daili->where($w)->select();//echo $daili->_sql();die;
						}
					}
					if(I('post.sdate')!="" AND I('post.edate')!="")
					{   
						$arr['regtime']=array('between',array(I('post.sdate'),I('post.edate')));
						$sql=$daili->where($arr)->where('superior='.$_SESSION['accounts'])->select();//echo $daili->_sql();die;

						if($_SESSION['agencylv']==0)
						{
						    $sqls = array();
						    $a = I("post.sdate"); $b = I("post.edate");
							foreach ($cate as $key => $value) {
					
								$sql1 = "select * from t_agent_add_cards_to_agent where recipient =".$value['accounts']." and regtime between '$a' and '$b'";
								//dump($sql1);die;
								array_push($sqls, $sql1);
							}
							
				  	      	$var = get_age(M(), $sqls);//调用函数
				  	      	$sql = array();
				  	      	
				  	      	foreach($var as $value){  
							    foreach($value as $v){  
							         $sql[]=$v;  
							    }  
							}
						}
						if($_SESSION['agencylv']==100)
						{
						    
							$sql=$daili->where($arr)->select(); 
						}
					}	
				}
			}
            
			$this->assign('sql',$sql);
			$this->display();
		}
		//我的下级的购钻记录
		public function agentbuygold()
		{  
			login('请先登录');
		    $getAccounts = I('get.accounts');
		    //dump($getAccounts);die;
			$sql=M('t_agent_add_cards_to_agent')->where('recipient='.$getAccounts)->order('regtime desc')->select();
			$arr['regtime']=array('between',array(I('post.sdate'),I('post.edate')));
			if(IS_POST)
			{//dump($_POST);die;
				if(I('post.type')!="")
				{
					if(I('post.type')==1)															//传过来的查询方式为1 要执行的
					{
						$sql=M('t_agent_add_cards_to_agent')->where('manner=3 AND recipient='.$getAccounts)->order('regtime desc')->select();
					}							
					if(I('post.type')==0)															//传过来的查询方式为1 要执行的
					{
						$sql=M('t_agent_add_cards_to_agent')->where('recipient='.$getAccounts)->order('regtime desc')->select();
					}
					if(I('post.type')==2)  															//传过来的查询方式为2 要执行的
					{
						$sql=M('t_agent_add_cards_to_agent')->where('manner=2 AND recipient='.$getAccounts)->order('regtime desc')->select();//echo M('t_agent_add_cards_to_agent')->_sql();die;
					}
				}

				if(I('post.sdate')!="" AND I('post.edate')!="")
				{
					$sql=M('t_agent_add_cards_to_agent')->where($arr)->where('recipient='.$getAccounts)->select();
				}
			}	
			$this->assign('sql',$sql);
			$this->display();
		}
		/*---------更改密码---------*/
		public function modipass()
		{    
			$id = I('get.accounts');
			if(IS_POST)
			{
				if(I('post.ppass')=="" || I('post.cword')=="")
				{
					echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					echo "<script type='text/javascript'>alert('密码不能为空');history.go(-1)</script>";die;
				}
				if(I('post.ppass')!=I('post.cword'))
				{ 
					echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					echo "<script type='text/javascript'>alert('您输入的新密码和确认密码不一致，请重新输入');history.go(-1)</script>";die;
				}
				if(strlen(I('post.ppass'))<6 || strlen(I('post.cword')<6))
				{
					echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					echo "<script type='text/javascript'>alert('密码不符合规范性');history.go(-1)</script>";die;
				}
				if(MD5(I('post.ppass'))==MD5(I('post.cword')))
				{
					$ppass=MD5(I('post.ppass'));
					if(M("","","DB_CONFIG0")->execute("update t_agent set password='$ppass' where accounts=".I('get.accounts')))
					{
						myadmin('密码重置成功，请保管好您的密码。');
					}else
					{
						error_add('系统繁忙，请您重再次输入');
					}
				}
			}
			$this->assign('id',$id);
			$this->display();
		}
		/*---------代理充值钻石页面---------*/
		public function ChargeGoldToAgent()
		{    
				


			$daili=M('t_agent');
			$pre=M('t_agent_add_cards_to_agent');
			$userid=I('get.userid');//接受方  																								
			$singleAgentInfo=$daili->where('userid='.$userid)->find(); //接收方的数据	

			$message=$daili->where('accounts='.$_SESSION['accounts'])->find();//登录的用户数据 	

			$Regems=I('post.gems2');	//要冲的钻石

			$new=$message['gems']-$Regems;// 登录用户的钻石量减去要充值的钻石量	
			
			$add=$singleAgentInfo['gems']+$Regems;//用户增加后的钻石数量																			
			//写入充值记录
			$date['manner']=$_POST['fangshi'];//接收方接受钻石的方式                    																
			$date['benefactor']=$message['accounts'];//赠送方（登录）的用户账号

			$date['recipient']=$singleAgentInfo['accounts'];//接收方的用户账号

			$date['up_id']=$up_id2['accounts'];//接收方的上上级账号	

			$date['gems']=$Regems;	//赠送的钻石数	

			$date['properties']=0;	//接收人属性

			$date['gems_front']=$message['gems'];//赠送前的钻石数	

			$date['gems_queen']=$new;		//赠送后的钻石数

			$date['accept_frone']=$singleAgentInfo['gems'];	//用户接收前的钻石数量	

			$date['accept_queen']=$add;	//用户接收后的钻石数量	

			$date['superior']=$low['accounts'];	//接收方的上级账号	 	
			$date['sort']=0;
			if(IS_POST)	
			{				
				if($Regems<=0)
				{
					error_add('您好，请输入正确的充值数量');
				}
				if($Regems > $message['gems'])	
				{		
					error_add('您好，您的账号上钻石数不足，无法充值，请联系上级或自行充值');
				}
				/*----------赠送----------*/
				if($_POST['fangshi']==2)
				{
					//玩家被充值后
					if($pre->add($date))
					{
						//dump($singleAgentInfo['accounts']);die;
						$daili->where('accounts='.$message['accounts'])->setField('gems',$new); //更改登录用户的钻石，充值后
						$daili-> where('accounts='.$singleAgentInfo['accounts'])->setField('gems',$add);

						error_add_four($singleAgentInfo,$Regems);
					}
					else
					{
						error_add('系统繁忙，请您重再次充值');
					}	
				}
			}

			
			$this->assign('singleAgentInfo',$singleAgentInfo);
			$this->display();
		}				
		/*---------我的购钻记录---------*/
		public function buygold()
		{   
			login('请先登录');
		    
			$sql=M('t_agent_add_cards_to_agent')->where('recipient='.$_SESSION['accounts'])->order('regtime desc')->select();	//查询出所有的数据
			//dump($sql);die;
			
			$arr['regtime']=array('between',array(I('post.sdate'),I('post.edate')));
			
			if($_SESSION['agencylv']==100)
			{
				$sql=M('t_agent_add_cards_to_agent')->order('regtime desc')->select();
			}
			if(IS_POST)
			{//dump($_POST);die;
				if(I('post.type')!="")
				{
					if(I('post.type')==1)	//传过来的查询方式为1 要执行的
					{
						$sql=M('t_agent_add_cards_to_agent')->where('manner=3 AND recipient='.$_SESSION['accounts'])->order('regtime desc')->select();
						if($_SESSION['agencylv']==100)
						{
							$sql=M('t_agent_add_cards_to_agent')->where('manner=3')->order('regtime desc')->select();//echo M('t_agent_add_cards_to_agent')->_sql();die;
							
						}
					}							
					if(I('post.type')==0)	//传过来的查询方式为0 要执行的
					{
						$sql=M('t_agent_add_cards_to_agent')->where('recipient='.$_SESSION['accounts'])->order('regtime desc')->select();
						if($_SESSION['agencylv']==100)
						{
							$sql=M('t_agent_add_cards_to_agent')->order('regtime desc')->select();
						}
					}
					if(I('post.type')==2) //传过来的查询方式为2 要执行的
					{
						$sql=M('t_agent_add_cards_to_agent')->where('manner=2 AND recipient='.$_SESSION['accounts'])->order('regtime desc')->select();//echo M('t_agent_add_cards_to_agent')->_sql();die;
						if($_SESSION['agencylv']==100)
						{
							$sql=M('t_agent_add_cards_to_agent')->where('manner=2')->order('regtime desc')->select();
						}
					}
				}

				if(I('post.sdate')!="" AND I('post.edate')!="")
				{
					$sql=M('t_agent_add_cards_to_agent')->where($arr)->where('recipient='.$_SESSION['accounts'])->select();
					if($_SESSION['agencylv']==100)
					{
						$sql=M('t_agent_add_cards_to_agent')->where($arr)->select();
					}
				}
			}	
			$this->assign('sql',$sql);
			$this->display();
		}
		/*---------修改代理信息---------*/
		public function agentmodi()
		{
			$daili=M('t_agent');
			$userid=I('get.userid');
			$sql=$daili->where('userid='.$userid)->find();	//SQL查询语句
			if($_POST)
			{
				if(I('post.username')=="" || I('post.nickname')=="" )
				{
					error_add('请详细填写信息');
				}
				$daili->username=I('post.username');
				$daili->nickname=I('post.nickname');
				$daili->region=I('post.region');
				if(I('post.username')!="" || I('post.nickname')!="" || I('post.region')!="" )
				{
					if($daili->where('userid='.$userid)->save())
					{
						myadmin('修改信息成功');
					}
					else
					{
						error_add('您并未修改信息，请返回');
					}
				}
			}	
			$this->assign('sql',$sql);
			$this->display();
		}	
		/*---------赠送玩家记录---------*/
		public function playercharge()
		{
			login('请先登录');
			$daili=M('t_agent_add_cards_to_user');
			$sql=$daili->where('benefactor='.$_SESSION['accounts'])->order('regtime desc')->select();//要查询的数据
			
			if($_SESSION['agencylv']==0)
				{
					$cate = array();
	                $va = get_str(M());
	                $va($cate,$_SESSION['accounts']);
					$sqls = array();
					foreach ($cate as $key => $value) {
						
						$sql1 = "select * from t_agent_add_cards_to_user where benefactor =".$value['accounts'];
						array_push($sqls, $sql1);
					}
					$sql2 = "select * from t_agent_add_cards_to_user where benefactor =".$_SESSION['accounts'];
					array_push($sqls, $sql2);
		  	      	$var = get_age(M(),$sqls);//调用函数
		  	      	$sql = array();
		  	      	
		  	      	foreach($var as $values){  
					    foreach($values as $v){  
					         $sql[]=$v;  
					    }  
					}
				}

			//dump($var);die;

			if($_SESSION['agencylv']==100)
			{
				$sql=$daili->order('regtime desc')->select();
			}			
			if(IS_POST)
			{		
				
				if(I('post.accounts')!="")
				{
					$w['recipient']=array('like','%'.I('post.accounts').'%');//把数据写到空数组去
					$sql=$daili->where($w)->where('benefactor='.$_SESSION['accounts'])->select();

					if($_SESSION['agencylv']==0)
					{
						$cate = array();
		                $va = get_str(M());
		                $va($cate,$_SESSION['accounts']);
						$sqls = array();
						foreach ($cate as $key => $value) {
							
							$sql1 = "select * from t_agent_add_cards_to_user where benefactor =".$value['accounts']." and recipient like '%".I('post.accounts')."%'";
							//dump($sql1);die;
							array_push($sqls, $sql1);
						}
						$sql2 = "select * from t_agent_add_cards_to_user where benefactor =".$_SESSION['accounts']." and recipient like '%".I('post.accounts')."%'";
					    array_push($sqls, $sql2);
			  	      	$var = get_age(M(),$sqls);//调用函数
			  	      	$sql = array();
			  	      	
			  	      	foreach($var as $values){  
						    foreach($values as $v){  
						         $sql[]=$v;  
						    }  
						}
					}

					if($_SESSION['agencylv']==100)
					{
						$sql=$daili->where($w)->select();
					}
					

					if(!isset($sql))
					{
						error_add('搜索内容不存在');
					}
				}
				if(I('post.sdate')!="" AND I('post.edate')!="")
				{
					$arr['regtime']=array('between',array(I('post.sdate'),I('post.edate')));
					$sql=$daili->where($arr)->where('benefactor='.$_SESSION['accounts'])->select();//echo $daili->_sql();die;

					if($_SESSION['agencylv']==0)
					{
						$cate = array();
		                $va = get_str(M());
		                $va($cate,$_SESSION['accounts']);
						$sqls = array();
						$a = I("post.sdate"); $b = I("post.edate");
						foreach ($cate as $key => $value) {
							
							$sql1 = "select * from t_agent_add_cards_to_user where benefactor =".$value['accounts']." and regtime between '$a' and '$b'";
							//dump($sql1);die;
							array_push($sqls, $sql1);
						}
						$sql2 = "select * from t_agent_add_cards_to_user where benefactor =".$_SESSION['accounts']." and regtime between '$a' and '$b'";
					    array_push($sqls, $sql2);
			  	      	$var = get_age(M(),$sqls);//调用函数
			  	      	$sql = array();
			  	      	
			  	      	foreach($var as $values){  
						    foreach($values as $v){  
						         $sql[]=$v;  
						    }  
						}
					}

					if($_SESSION['agencylv']==100)
					{
						$sql=$daili->where($arr)->select();//echo $daili->_sql();die;
					}
				}
			}
			    $sql = sortArrayDesc($sql,'regtime');//按时间倒叙排序
				$this->assign('sql',$sql);
				$this->display();
		}
			/*---------代理的信息---------*/
		public function myinfo()
		{
			login('请先登录');
			$daili=M('t_agent');
			if(I('get.accounts')=="")
			{
				$sql=$daili->where('accounts='.$_SESSION['accounts'])->find();//sql查询后的结果
			}else
			{
				$sql=$daili->where('accounts='.I('get.accounts'))->find();
			}
			$this->assign('sql',$sql);
			$this->display();
		}
			/*---------消息通知---------*/
		public function setnotice()
		{
			login('请先登录');
			$sql=M('t_msg')->find();//sql查询语句
			if(IS_POST)
			{
				$content=I('post.content');
				if(M("","","DB_CONFIG0")->execute("update t_msg set content='$content' where userid=1"))	//更改充值用户的钻石
				{
					indexx('修改成功');
				}else
				{
					indexx('未作修改,请确认操作');
				}
			}
			$this->assign('sql',$sql);
			$this->display();
		}	
			/*---------代理政策---------*/
		public function policy(){
			$picture=M("t_msg")->find();
			$this->assign('picture',$picture);
			$this->display();
			}		
			/*---------政策管理---------*/
		public function policyedit()
		{
		   login('请先登录');
			$picture=M("t_msg")->find();
			if(IS_POST)
			{	
				$imgsrc="";
				if($_FILES['file']['error']==0)
				{
					$imgsrc=$this->uploadOne($_FILES['file']);				
				}else
				{
					$imgsrc=I('post.pid');
				}
				$shu=M('t_msg');
				$shu->create();
				$shu->tupian=$imgsrc;
				$shu->content=$picture['content'];
				if($shu->where('userid=1')->save())
				{
					policy('更改成功');
				}else
				{
					error_add('未做更改');
				}	
			}
			$this->assign('picture',$picture);
			$this->display();
		}	
		public function uploadOne($file)
		{   
			$upload = new \Think\Upload();											// 实例化上传类    
			$upload->maxSize   =     3145728 ;										// 设置附件上传大小    
			$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');			// 设置附件上传类型    
			$upload->savePath  =      ''; 											// 设置附件上传目录    // 上传单个文件     
			$info=$upload->uploadOne($file);    
			if(!$info)
			{																		// 上传错误提示错误信息            
				$this->error($upload->getError());       
			}else
			{																		// 上传成功 获取上传文件信息    
				return $info['savepath'].$info['savename']; 
			}
		}  	
		//支付页面	
		public function payoff()
		{
		   login('请先登录');
		   $this->display();        
		}
		
		public function Userrecharge()
		{
			$userId = trim($_GET["userId"]);
			$money = trim($_GET["money"]);
			$goodsNum = trim($_GET["goodsNum"]);
			$type = trim($_GET["type"]);
			$give = trim($_GET["give"]);
			$unit = '钻石';
			
			//dump($userId);
			//dump($money);
			//dump($goodsNum);
			//dump($type);
			//dump($give);
			if ($type==1)
			{
				$unit = '酒豆';
			}

			$this->assign('userId',$userId);
			$this->assign('money',$money);
			$this->assign('goodsNum',$goodsNum);
			$this->assign('type',$type);
			$this->assign('give',$give);
			$this->assign('unit',$unit);
			$this->display();
		}
		
		public function payoff_mobile_callback(){
						
			$state=trim($_GET["state"]);            	// 1:充值成功 2:充值失败
			$customerid=trim($_GET['customerid']);		//商户注册的时候，网关自动分配的商户ID
			$sd51no=trim($_GET["sd51no"]);          	//该订单在网关系统的订单号
			$sdcustomno=trim($_GET["sdcustomno"]);  	//该订单在商户系统的流水号
			$ordermoney=trim($_GET["ordermoney"]);  	//商户订单实际金额单位：（元）
			$cardno=trim($_GET["cardno"]);          	//支付类型，为固定值 32
			$mark=trim($_GET['mark']);              	//未启用暂时返回空值
			$sign=trim($_GET['sign']);              	//发送给商户的签名字符串
			$resign=trim($_GET["resign"]);          	//发送给商户的签名字符串
			$des=trim($_GET["des"]);                	//描述订单支付成功或失败的系统备注
			$key='244ca72c106b8eef6c27f2e97bfd93ee';
			$mark = "coinsforplayers";
			$customerid = "155038";
			$Md5str='customerid='.$customerid.'&sdcustomno='.$sdcustomno.'&mark='.$mark.'&key='.$key;
			$params = array(
	    	'customerid' => $customerid,
	    	'sdcustomno' => $sdcustomno,
	    	"sign" => strtoupper(md5($Md5str)),
	    	"mark" => $mark,
	        );
			
			//dump($_GET);
			$sign2=strtoupper(md5("customerid=".$customerid."&sd51no=".$sd51no."&sdcustomno=".$sdcustomno."&mark=".$mark."&key=".$key));
			$resign2=strtoupper(md5("sign=".$sign."&customerid=".$customerid."&ordermoney=".$ordermoney."&sd51no=".$sd51no."&state=".$state."&key=".$key));
	
			if($sign!=$sign2)
			{
				echo "sign签名不正确";
				//记录日志
				//exit();
			}
			
			if($resign!=$resign2)
			{
				echo "resign签名不正确";
				//记录日志
				//exit();
			}
		
			//**************************************************************************
			//*第三步
			//*商户系统业务逻辑处理
			//**************************************************************************
			$bSuccess = 1;
			if($state=="1")
			{
				//当充值成功后同步商户系统订单状态
				//此处编写商户系统处理订单成功流程
				//............
				//............
				//$sql = "LOCK TABLES yp_apply_order WRITE";
				//M("","","DB_CONFIG0")->execute($sql);
				$zt = M('yp_apply_order')->where('order_status = 1 and order_no='.$sdcustomno)->find();
				if ($zt == "") {
					//$expro = "call sp_update_recharge_result('".$sdcustomno."','".$sd51no."','".$sign."')";
					//dump($expro);
					M("","","DB_CONFIG0")->execute("call sp_update_recharge_result('".$sdcustomno."','".$sd51no."','".$sign."')");
					$bSuccess = 1;
				} else {
					$bSuccess = 2;
					//dump("has operate db ");
				}
				//$sql = "UNLOCK TABLES";
				//M("","","DB_CONFIG0")->execute($sql);
				
				//商户在接受到网关通知时，应该打印出<result>1</result>标签，以供接口程序抓取信息，以便于我们获取是否通知成功的信息，否则订单会显示没有通知商户
				echo "<result>1</result>";
				//记录订单处理日志
			}
			else if($state=="2")
			 {
				//当充值失败后同步商户系统订单状态
				//此处编写商户系统处理订单失败流程
				//............
				//............
				//商户在接受到网关通知时，应该打印出<result>1</result>标签，以供接口程序抓取信息，以便于我们获取是否通知成功的信息，否则订单会显示没有通知商户
				echo "<result>1</result>";
				//记录订单处理日志
				$bSuccess = 0;
			}
			else{
				//异常处理部分（可选）,根据自己系统而定
				echo "<result>0</result>";   //当返回<result>0</result>时星启天网关系统会继续通知
				//记录订单处理日志
				$bSuccess = 0;
			}
			echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
			if ($bSuccess == 0){
				echo "<script type='text/javascript'>alert('支付失败!');</script>";
			}else {
				echo "<script type='text/javascript'>alert('支付成功!');</script>";
			}
		}
		
		public function payoff_mobile()
		{
			//接收回调数据
			$state			= trim($_GET["state"]);            	 // 1:充值成功 2:充值失败
			$sd51no			= trim($_GET["sd51no"]);          	 //该订单在网关系统的订单号
			$sdcustomno		= trim($_GET["sdcustomno"]);  		 //该订单在商户系统的流水号
			$orderMoney		= trim($_GET["ordermoney"]);  		 //商户订单实际金额单位：（元）
			$sign			= trim($_GET['sign']);               //发送给商户的签名字符串
			$key			= '244ca72c106b8eef6c27f2e97bfd93ee';

			//dump($_GET);
			$sign2=strtoupper(md5("sdcustomno=".$sdcustomno."&state=".$state."&sd51no=".$sd51no."&orderMoney=".$orderMoney."&key=".$key));
			if($sign!=$sign2)
			{
				echo "sign is not correct";
				dump($sign);
				dump($sign2);
				//exit();
			}
		
			$bSuccess = 1;
			if($state=="1")
			{
				//当充值成功后同步商户系统订单状态
				//商户在接受到网关通知时，应该打印出<result>1</result>标签，以供接口程序抓取信息，以便于我们获取是否通知成功的信息，否则订单会显示没有通知商户
				//echo "<result>1</result>";

				//$sql = "LOCK TABLES yp_apply_order WRITE";
				//M("","","DB_CONFIG0")->execute($sql);
				//$zt = M('yp_apply_order')->where('order_status = 1 and order_no='.$sdcustomno)->find();
				//if ($zt == "") {
					//$expro = "call sp_update_recharge_result('".$sdcustomno."','".$sd51no."','".$sign."')";
					//dump($expro);
					//M("","","DB_CONFIG0")->execute("call sp_update_recharge_result('".$sdcustomno."','".$sd51no."','".$sign."')");
					$bSuccess = 1;
				//} else {
					//$bSuccess = 2;
					//dump("has operate db ");
				//}
				//$sql = "UNLOCK TABLES";
				//M("","","DB_CONFIG0")->execute($sql);
			}
			else if($state=="2")
			{
				//当充值失败后同步商户系统订单状态
				//商户在接受到网关通知时，应该打印出<result>1</result>标签，以供接口程序抓取信息，以便于我们获取是否通知成功的信息，否则订单会显示没有通知商户
				//echo "<result>1</result>";
				//记录订单处理日志
				$bSuccess = 0;
			}
			else
			{
				//异常处理部分（可选）,根据自己系统而定
				//echo "<result>0</result>";   //当返回<result>0</result>时星启天网关系统会继续通知
				//记录订单处理日志
				$bSuccess = 0;
			}
	
			if ($bSuccess > 0){
				//echo "<script type='text/javascript'>alert('支付失败!');</script>";
				echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
				echo "<script type='text/javascript'>alert('支付成功!');</script>";
			}
		}
		public function payoff_jump()
		{  
			login('请先登录');
			//接收回调数据
			$state=trim($_GET["state"]);            	// 1:充值成功 2:充值失败
			$customerid=trim($_GET['customerid']);		//商户注册的时候，网关自动分配的商户ID
			$sd51no=trim($_GET["sd51no"]);          	//该订单在网关系统的订单号
			$sdcustomno=trim($_GET["sdcustomno"]);  	//该订单在商户系统的流水号
			$orderMoney=trim($_GET["orderMoney"]);  	//商户订单实际金额单位：（元）
			$cardno=trim($_GET["cardno"]);          	//支付类型，为固定值 32
			$mark=trim($_GET['mark']);              	//未启用暂时返回空值
			$sign=trim($_GET['sign']);              	//发送给商户的签名字符串
			$resign=trim($_GET["resign"]);          	//发送给商户的签名字符串
			$des=trim($_GET["des"]);                	//描述订单支付成功或失败的系统备注
			$key='244ca72c106b8eef6c27f2e97bfd93ee';
			$mark = "diamond for players";
			$customerid = "155038";
			$Md5str='customerid='.$customerid.'&sdcustomno='.$sdcustomno.'&mark='.$mark.'&key='.$key;
			$params = array(
	    	'customerid' => $customerid,
	    	'sdcustomno' => $sdcustomno,
	    	"sign" => strtoupper(md5($Md5str)),
	    	"mark" => $mark,
	        );

	        $zt = M('yp_apply_order')->where('order_status = 1 and order_no='.$sdcustomno)->find();
	        //dump($zt);die;
            if ($zt != "") {
                echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
				echo "<script type='text/javascript'>alert('支付成功');location.href='http://".$_SERVER['SERVER_NAME']."/zy_agent/payoff.html'</script>";
            }else{
            	
				M("","","DB_CONFIG0")->execute("update yp_apply_order set order_status='$state' where order_no=".$sdcustomno);
				$zz=M('yp_apply_order')->where('order_no='.$sdcustomno)->find();//微信充值订单	
				//$yp_order_record=M('yp_order_record');	//订单状态表

				if($_GET['orderMoney']==0.01)
				{
					$Regems=400;//充值钻石数
				}			
				if($_GET['orderMoney']==0.03)
				{
					$Regems=1300;
				}			
				if($_GET['orderMoney']==0.1)
				{
					$Regems=4600;
				}			
				if($_GET['orderMoney']==0.3)
				{
					$Regems=15000;
				}			
				
				$RMB = $_GET['orderMoney']*10000;//充值金额，测试用

				if($zz=="")
				{
					echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					echo "<script type='text/javascript'>alert('支付错误，请联系客服');location.href='payoff'</script>";die;	
				}

					$daili=M('t_agent');//代理信息表

					$pre=M('t_agent_add_cards_to_agent');//代理充值赠送表

					$message=$daili->where('accounts='.$zz['oper_account'])->find(); //登录的用户数据

				    $totalhistory=M('t_agent_add_cards_to_agent')->where('manner=3 AND recipient='.$_SESSION['accounts'])->sum('gems');
					//$totalhistory=M('yp_apply_order')->where('order_status=1')->where('customer_id='.$_SESSION['accounts'])->sum('order_gems');//微信充值总数
				    M('t_agent')->execute("update t_agent set totalhistory='$totalhistory' where accounts=".$_SESSION['accounts']);
	                //微信充值总数写进代理表
	                
					/*------------代理级别与总代理级别达到三级及以上向总代理的返利写入返利表（t_rebate）----------*/
					$cate = array();
		  	     	$va = get_bate(M());
		  	     	$count = 0;
					$va($cate, $message['referrer'], $count);
					// $cate[0]['accounts'];//充钻人的上级总代理
					// $message['disbate'];//向总代理返利数量
					

					if($count >=3){
						$highest = $daili->where('accounts='.$cate[0]['accounts'])->find();	//最高层代理信息

						if ($highest['agencylv'] == 0) {
							$rechargetotal01 = $highest['rechargetotal'] + $RMB;
					        M("","","DB_CONFIG0")->execute("update t_agent set rechargetotal='$rechargetotal01' where accounts=".$highest['accounts']);
						}

				    	$disbate = M('t_rebate_quota')->where("id=".$cate[0]['accounts'])->find();//向最高层代理返利额度

				    	$dis = floor($Regems*$disbate['disbate']);//向最高层代理返利数
	                }

	                if($count>=1){ 

						$superior=$daili->where('accounts='.$message['referrer'])->find();		//登录用户的上级代理数据

	                    $rechargetotal02 = $superior['rechargetotal'] + $RMB;

					    M("","","DB_CONFIG0")->execute("update t_agent set rechargetotal='$rechargetotal02' where accounts=".$superior['accounts']);

						$quota = M('t_rebate_quota')->where("id =".$superior['accounts']." AND top_limit >".$superior['rechargetotal']." AND botton_limit <=".$superior['rechargetotal'])->find();//登录用户的上级代理返利额度
				    }

	                if($count>=2){ 

						$up_superior=$daili->where('accounts='.$superior['referrer'])->find();	//登录用户的上上级代理数据	

						$rechargetotal03 = $up_superior['rechargetotal'] + $RMB;

					    M("","","DB_CONFIG0")->execute("update t_agent set rechargetotal='$rechargetotal03' where accounts=".$up_superior['accounts']);

		                $up_quota = M('t_rebate_quota')->where("id =".$up_superior['accounts']." AND top_limit >".$up_superior['rechargetotal']." AND botton_limit <=".$up_superior['rechargetotal'])->find();//登录用户的上上级代理返利额度
					}

					//将登陆账户的充值信息写进充值赠送表（t_agent_add_cards_to_agent）----------------*/
					
					$date['gems']= $Regems;	//充值钻石数

					$date['sort']=3;//3为微信扫码方式支付
					
					$date['manner']=3;	//3为微信扫码方式支付	2为代理赠送																			
					$date['benefactor']=0;		//0为微信扫码充值或者为赠送账号

					$date['recipient'] = $message['accounts'];	//被充值的人

	                if($count>=1){
						$date['superior']=$superior['accounts'];	//登录用户的上级ID
	                }

	                if($count>=2){
						$date['up_id']=$up_superior['accounts'];	//登录用户的上上级ID
	                }

					$date['properties']=0;	//接收人属性默认0

					$date['accept_frone']=$message['gems'];	//接收前的钻石

					$date['accept_queen']=$message['gems']+$Regems;	//接收后的钻石

					
				
					/*------------被充值上级代理的等级为1的返利写入返利表（t_rebate）----------------*/
					
					$date2['benefactor']=3;	//充钻方式为微信充值

					$date2['recipient']=$message['accounts'];	//被充钻账号

					$date2['gems']=$Regems;//充钻数量

					$date2['superior_id']=$superior['accounts'];//充钻人的上级

					$date2['order_no']=$sdcustomno;	//订单号

					
					$date2['accumulative']=floor($Regems*$quota['first_upper_rebate']);//向上级返利数量
					
					/*------------被充值代理的等级为2代理的返利写入返利表（t_rebate）---------------*/
					$date3['benefactor']=3;	//充钻方式为微信充值

					$date3['recipient']=$message['accounts'];//被充钻账号	

					$date3['gems']=$Regems;//充钻数量	

					$date3['accumulative']=floor($Regems*$quota['first_upper_rebate']);//向上级返利数量

					$date3['superior']=floor($Regems*$up_quota['second_upper_rebate']);//向上上级返利数量

					$date3['superior_id']=$superior['accounts'];//充钻人的上级

					$date3['up_id']=$up_superior['accounts'];//充钻人的上上级

					$date3['order_no']=$sdcustomno; //订单号

					
	 
					$t_rebate = M('','t_rebate','DB_CONFIG0'); //返利表

					$rebate=M('t_rebate')->where('order_no='.$sdcustomno)->find(); 	//订单号是否存在

					if($rebate == "")//
					{    
						$pre->add($date);//将充值信息写入代理充值赠送表

						if($count==1)//当充值用户的上级只有1层的时候向上级返利
						{		
						    $t_rebate->add($date2);	//写入返利表															
						}
						elseif($count>=2)
						///当充值用户的上级有2层的时候,向上级及上上级返利
						{	
							$t_rebate->add($date3);	//写入返利表			
						}
						if($count >= 3 && $highest['agencylv'] == 0){//当本账户等级与总代理相隔达到3层及以上，将固定返利写入返利表

							M("","","DB_CONFIG0")->execute("update t_rebate set distributor=".$cate[0]['accounts'].",
								todisbate = ".$dis." where order_no=".$sdcustomno);	
						}

					}else{
						echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
						echo "<script type='text/javascript'>alert('订单完成记录不存在');location.href='http://".$_SERVER['SERVER_NAME']."/zy_agent/payoff.html'</script>";die;	
					}	

					if($state=="1")	// 订单成功的操作    
					{
						$yp_order_record=M('yp_order_record');//订单状态表

						$order_gems=$message['gems']+$Regems;//充值后获得钻石后钻石的总数

						M("","","DB_CONFIG0")->execute("update t_agent set gems='$order_gems' where accounts=".$message['accounts']);	//更改充值用户的钻石
						
						$sql=$yp_order_record->where('order_no='.$sdcustomno)->find();// 订单是否已经存在

						if($sql=="")//当订单不存在时的操作
						{					
							M('','','DB_CONFIG0')->execute("insert into yp_order_record(order_no,state,gateway_no,fill_money,sign,order_gems)values('$sdcustomno','$state','$sd51no','$orderMoney','$sign','$order_gems')");//写进订单状态表

							echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
							echo "<script type='text/javascript'>alert('支付成功');location.href='http://".$_SERVER['SERVER_NAME']."/zy_agent/index.html'</script>";
						}
						else//当订单存在时的操作
						{
							echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
							echo "<script type='text/javascript'>alert('订单完成记录已存在!');location.href='http://".$_SERVER['SERVER_NAME']."/zy_agent/payoff.html'</script>";die;
						}
					}
					else if($state=="2")// 订单处理中
					{
						M('','','DB_CONFIG0')->execute("insert into yp_order_record(order_no,state,gateway_no,fill_money,sign)values('$sdcustomno','$state','$sd51no','$orderMoney','$sign')");
						echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
						echo "<script type='text/javascript'>alert('系统繁忙');location.href='http://".$_SERVER['SERVER_NAME']."/zy_agent/payoff.html'</script>";
					}
		    }
			
			 $this->display();
		}		
}
